package com.fanix5.javamvvm.base;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.Toolbar;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;

import com.fanix5.javamvvm.R;
import com.fanix5.javamvvm.utils.StatusBarUtil;

import java.lang.ref.WeakReference;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class MvvmBaseActivity<DB extends ViewDataBinding, VM extends BaseViewModel> extends AppCompatActivity  {

    protected DB mDatabind;
    protected VM mViewModel;
    private int viewModelId;
    private Handler handler;

    /**
     * 当前Activity的实例。
     */
    protected Activity activity;
    /**
     * 当前Activity的弱引用，防止内存泄露
     */
    private WeakReference<Activity> activityWR;


    /**
     * 日志输出标志
     */
    protected String TAG = this.getClass().getSimpleName();



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(getScreenOrientation());//竖屏
        //绑定DataBinding
        mDatabind = DataBindingUtil.setContentView(this, getLayoutId());

        viewModelId = initVariableId();

        try {
            if (mViewModel == null) {
                Class modelClass;
                Type type = getClass().getGenericSuperclass();
                if (type instanceof ParameterizedType) {
                    modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1];
                } else {
                    //如果没有指定泛型参数，则默认使用BaseViewModel
                    modelClass = BaseViewModel.class;
                }
                mViewModel = (VM) new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(modelClass);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        mDatabind.setVariable(viewModelId, mViewModel);
        mDatabind.executePendingBindings();
        //支持LiveData绑定xml，数据改变，UI自动会更新
        mDatabind.setLifecycleOwner(this);


        // setContentView(getLayoutId());
        activity = this;
        activityWR = new WeakReference<Activity>(activity);
        ActivityStackManager.getInstance().addActivity(activityWR);
        initView();
        initViewObservable();
        handler = new Handler(Looper.getMainLooper());
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initData();
            }
        },300);

        initListener();
        Log.e(TAG, "stackSize1: " + ActivityStackManager.getInstance().stackSize());
    }

    protected int getScreenOrientation() {
        return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    }

    /**
     * 设置toolbar
     */
    public void setToolBar(Activity activity, Toolbar toolBar, boolean lightColor, String title) {
        View view1 = findViewById(R.id.statusBar);
        StatusBarUtil.getInstance().setBar(activity, view1, lightColor);
        toolBar.setNavigationIcon(R.drawable.ic_action_back_white);
        toolBar.setNavigationOnClickListener(v -> onReturn());
        if (title != null) {
            AppCompatTextView titleTextView = findViewById(R.id.toolText);
            titleTextView.setGravity(Gravity.CENTER);
            titleTextView.setText(title);
        }
    }

    public void onReturn() {
        finish();
    }

    /**
     * 跳转页面
     *
     * @param clz 所跳转的目的Activity类
     */
    public void startActivity(Class<?> clz) {
        startActivity(new Intent(this, clz));
    }

    /**
     * 跳转页面
     *
     * @param clz    所跳转的目的Activity类
     * @param bundle 跳转所携带的信息
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }


    /**
     * 创建viewmodel
     *
     * @return
     */

    public ViewModelProvider getViewModel() {
        return new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory());
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "BaseActivity-->onDestroy()");

        if(handler != null){
            handler = null;
        }

        if (mDatabind != null) {
            mDatabind.unbind();
        }
        activity = null;
        ActivityStackManager.getInstance().removeActivity(activityWR);
        Log.e(TAG, "stackSize2: " + ActivityStackManager.getInstance().stackSize());

    }

    /**
     * 初始化ViewModel的id
     *
     * @return BR的id
     */
    protected abstract int initVariableId();

    /**
     * 获取布局 Id
     */
    protected abstract @LayoutRes
    int getLayoutId();

    /**
     * 初始化View的代码写在这个方法中
     */
    protected abstract void initView();

    /**
     * 页面事件监听的方法，一般用于ViewModel层转到View层的事件注册
     */
    protected abstract void initViewObservable(

    );


    /**
     * 初始化监听器的代码写在这个方法中
     */
    protected abstract void initListener();

    /**
     * 初始数据的代码写在这个方法中，用于从服务器获取数据
     */
    protected abstract void initData();

}
